package Logic.Objects;
import java.util.HashMap;
import java.util.Vector;
import Logic.IPlayer;
 
/* 
 * round	- what round (game number).
 * globalRoundPlace	- when object get notification of addNewScore,
 * 					  it save the player with the score of the value "globalRoundPlace"
 * 					  and increment globalRoundPlace by one.
 * 					  After the whole round, globalRoundPlace reach it's maximum == |Number Of Players -1|
 */
public class ScoreBoard{
	// when object get notification of addNewScore,
	// it save the player with the score of the value "globalRoundPlace"
	// and increment globalRoundPlace by one.
	// After the whole round, globalRoundPlace reach it's maximum == |Number Of Players -1|
	//int globalRoundPlace;


	// saves all players scores
	private static HashMap<IPlayer,Integer> playersScore = new HashMap<IPlayer,Integer>();

	
	/***********************<<< ScoreBoard CLASS OPERATIONS >>>******************/
	/**
	 * @param loserPlayers 
	 * @Description :
	 * 	check the player, if the player already scored in this round, throw Exception
	 * 	else, scored the player according to the score parameter (RoundScore.globalRoundPlace) of this round
	 * @param :
	 * 	IPlayer player
	 * 	int round
	 * @return:
	 * 	int - the score of the player
	 * @throws :
	 * 	Exception when the player hadn't scored  
	 */
	static public void addNewScore(IPlayer player, int score, Vector<IPlayer> loserPlayers){
		int newScore = score;
		if (playersScore.get(player) != null){
			newScore += playersScore.get(player);
		}
		if (loserPlayers == null){
			System.out.println("addNewScore: loserPlayers is a null vector");
			playersScore.put(player,newScore);
			return;
		}
		
		int BetterPlayersAvg = 0;
		int tscore = 0;
		int numOfBetterPlayers = 0;
		for (int playerNum=0; playerNum<loserPlayers.size(); playerNum++){
			try {
				tscore = getScore(loserPlayers.elementAt(playerNum));
			} catch (Exception e) {
				e.printStackTrace();
			}
			if (tscore > newScore){
				BetterPlayersAvg += tscore;
				numOfBetterPlayers++;
			}
		}
		if (BetterPlayersAvg > 0){
			BetterPlayersAvg /= numOfBetterPlayers;
			tscore = score;
			tscore *= Math.round((BetterPlayersAvg/newScore)/2);
			newScore += tscore - score;
		}
		
		playersScore.put(player,newScore);
	}
	
	/**
	 * @Description :
	 * 	return the score of "player" in the "round" round
	 * @param :
	 * 	IPlayer player
	 * 	int round
	 * @return:
	 * 	int - the score of the player
	 * @throws :
	 * 	Exception when the player hadn't scored  
	 */
	static public int getScore(IPlayer player) throws Exception{
		if (playersScore.get(player) == null){
			throw new Exception("Player"+player.getName()+"IsNotValid");
		}
		return playersScore.get(player);
	}
}
